<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :before-open="beforeOpen"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      :page.sync="page"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{row}"
                slot="source">
        <div style="text-align:center">
          <i :class="row.source"/>
        </div>
      </template>
      <template slot-scope="{row}" slot="time">
        <div>开始时间：{{row.time[0]}}</div>
        <div>结束时间：{{row.time[1]}}</div>
      </template>
      <template slot-scope="{row}" slot="status">
        <el-tag v-show="row.status==1">
          {{ transteStatus(row.status)}}
        </el-tag>
        <el-tag v-show="row.status==2" type="success">
          {{ transteStatus(row.status)}}
        </el-tag>
        <el-tag v-show="row.status==3" type="warning">
          {{ transteStatus(row.status)}}
        </el-tag>
        <el-tag v-show="row.status==4" type="info">
          {{ transteStatus(row.status)}}
        </el-tag>
      </template>
      <template slot-scope="{row}" slot="viewPicture">
        <el-button size="mini" @click="goToResource(row)">查看资源</el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
         <el-button
          type="text"
          icon="el-icon-view"
          size="small"
          @click="clickViewDetail(row)"
        >
         查看详情
        </el-button>
      </template>
    </avue-crud>
    <div v-if="openTaskFlag">
       <el-dialog
        title="查看详情"
        :visible.sync="openTaskFlag"
        width="50%"
        top="30px"
        :modal-append-to-body="false"
      >
        <el-tabs v-model="activeName" @tab-click="handleTabsClick">
          <el-tab-pane label="基本信息" name="first">
            <avue-form class="avue--detail" ref="addRef" :option="option" v-model='addFormData'>
              <template slot-scope="{row}" slot="status">
                {{ transteStatus(addFormData.status)}}
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="发布资源" name="second">
              <div v-html="resourceArr"></div>
          </el-tab-pane>
          <el-tab-pane label="审核资源" name="third">
             <el-empty v-if="feedbackResource.length==0" description="暂无审核数据！" :image-size="200"></el-empty>
             <div style="min-height:300px">
               <div class="aduit-box" v-for="(item,idx) in feedbackResource" :key="idx">
               <div class="left">
                  <div>
                    任务反馈记录{{idx}}
                  </div>
                    <div>
                      {{item.created_at}}
                    </div>
                    <div>
                      <el-tag v-show="item.status==1" type="info">
                        {{ transteRecoredStatus(item.status)}}
                      </el-tag>
                      <el-tag v-show="item.status==3" type="warning">
                        {{ transteRecoredStatus(item.status)}}
                      </el-tag>
                      <el-tag v-show="item.status==2" type="success">
                        {{ transteRecoredStatus(item.status)}}
                      </el-tag>
                    </div>
                    <div v-if="item.status==3" class="refuse-box">拒绝理由：{{item.refuseMark}}</div>
               </div>
               <div class="right" >
                 <el-button size="small" @click="viewCusDetail(item)">查看详情</el-button>
                 <el-button type="primary" size="small" v-if="item.status==1" @click="doAuditHandle(item,2)">通过</el-button>
                 <el-button type="danger" size="small" v-if="item.status==1" @click="doAuditRefuseHandle(item,3)">拒绝</el-button>
               </div>
              </div>
             </div>

          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
    <div v-show="openSourceFlag">
      <el-dialog
        title="查看客户上传资源"
        :visible.sync="openSourceFlag"
        width="50%"
        top="30px"
        :modal-append-to-body="false"
        :before-close="handleClose"
      >
        <el-tabs v-model="activeCusName">
          <el-tab-pane label="图片资源" name="cusFirst">
            <div style="min-height:300px;">
              <div class="img-box" v-for="(item,idx) in resourceImgArr" :key="idx">
                <img width="500px" :src="item" alt="">
                <div>
                    <el-divider></el-divider>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="文本资源" name="cusSecond">
            <div style="min-height:300px;color:#333;font-size:16px;">
               <div>{{feedRow.remark}}</div>
               <div v-if="feedRow.outUrl" style="margin-top: 10px;" @click="openOutUrl(feedRow.outUrl)"> <el-button type="primary" size="small">查看链接</el-button></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
    <div v-show="openRefuseFlag">
      <el-dialog
        title="拒绝理由"
        :visible.sync="openRefuseFlag"
        width="50%"
        :modal-append-to-body="false"
        :modal='false'
      >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="理由" prop="mark">
            <el-input v-model="ruleForm.mark"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="openRefuseFlag = false">取 消</el-button>
          <el-button type="primary" @click="doAuditRefuseConfirmHandle('ruleForm')">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </basic-container>
</template>
<script>
  import Dialog from '@/views/resource/dialog.vue'
  import {getList,findResourceByIds,weixinPay,getRecordList,doAudit} from "@/api/task/auittask";
  import {mapGetters} from "vuex";
  export default {
    components:{Dialog},
    data() {
      return {
        activeName:'first',
        activeCusName:"cusFirst",
        form: {},
        addFormData:{},
        box: false,
        openTaskFlag:false,
        openSourceFlag:false,
        submitLoading:false,
        resourceFlag:false,
        resourceArr:[],
        resourceImgArr:[],
        feedbackResource:[],
        feedRow:{},
        rowData:{},
        props: {
          label: "title",
          value: "key"
        },
        selectionList: [],
        query: {},
        loading: true,
        currolid:null,
        timer:null,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          selection: true,
          viewBtn: false,
          editBtn:false,
          addBtn:false,
          delBtn:false,
          dialogWidth: 900,
          dialogClickModal: false,
          labelWidth:110,
          columnBtn:false,
          height: 'auto',
          calcHeight: 40,
          viewDisabled: true,
          emptyBtn: false, //隐藏清空按钮
          submitBtn: false, //隐藏提交按钮
          column: [
            {
              label: "领取人",
              prop: "openId",
              width:100,
              readonly:true,
              span: 24,
            },
            {
              label: "任务名称",
              prop: "name",
              search:true,
              span: 12,
              readonly:true,
              showOverflowTooltip:true,
              rules: [
                {
                  required: true,
                  message: "请输入任务名称",
                  trigger: "blur"
                }
              ]
            },
             {
              align:'center',
              type:'number',
              label: "审核状态",
              prop: "status",
              readonly:true,
              span: 24,
              slot:true,
              formslot:true,
            },
            {
              label: "所属城市",
              prop: "city",
              type:'select',
              readonly:true,
              disabled:true,
              dicUrl: "/api/oms-system/base/citylist?current=1&size=1000",
              span: 12,
              search:true,
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              props: {
                label: "name",
                value: "id"
              },
            },
             {
              label: "所属平台",
              prop: "platForm",
              readonly:true,
               disabled:true,
              dicUrl: "/api/oms-system/base/platformlist?current=1&size=1000",
              span: 12,
              type:'select',
              search:true,
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              props: {
                label: "name",
                value: "id"
              },
            },
            {
              type:'number',
              label: "任务数量",
              prop: "num",
              align:'center',
              readonly:true,
              disabled:true,
              span: 12,
            },
            {
              type:'number',
              label: "奖励金额(元)",
              prop: "price",
              align:'center',
              readonly:true,
               disabled:true,
              span: 12,
              rules: [
                {
                  required: true,
                  message: "请输入任务金额",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "时间范围",
              prop: "time",
              align:'center',
              span: 24,
              width:200,
              readonly:true,
              type:'datetimerange',
              slot:true,
              rules: [
                {
                  required: true,
                  message: "请输入时间范围",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "所属行业",
              prop: "category",
              dicUrl: "/api/oms-system/base/categorylist?current=1&size=1000",
              type:'select',
              span: 12,
              width:90,
              readonly:true,
               disabled:true,
              props: {
                label: "name",
                value: "id"
              },
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
              rules: [{
                required: true,
                message: "请选择所属行业",
                trigger: "click"
              }]
            },
            {
              label: "所属广告商",
              prop: "advertise",
              dicUrl: "/api/oms-system/base/myadvertiserlist?current=1&size=1000",
              span: 12,
              width:120,
              readonly:true,
               disabled:true,
              align:'center',
              props: {
                label: "name",
                value: "id"
              },
              type:'select',
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
            },
            {
              label: "任务等级",
              prop: "taskgrade",
              dicUrl: "/api/oms-system/base/taskgradelist?current=1&size=1000",
              span: 12,
              readonly:true,
               disabled:true,
              props: {
                label: "name",
                value: "id"
              },
              type:'select',
              dicFormatter:res=>{
                 if(res && res.data && res.data.list.length){
                   return res.data.list
                 }else{
                   return []
                 }
              },
            },           
            {
              type:'textarea',
              label: "备注",
              prop: "remark",
              readonly:true,
              width:150,
              span:24,
              hide:false,
              showOverflowTooltip:true,
            },
            {
              label: "更新时间",
              prop: "updatedTime",
              width:150,
               span:24,
              readonly:true,
              align:'center'
            },
          ]
        },
        data: [],
        openRefuseFlag:false,
        ruleForm:{
          mark:''
        },
        rules: {
          mark: [
            { required: true, message: '请输入理由', trigger: 'blur' },
            { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
          ],
        },
        refuseItem:null
      };
    },
    computed: {
      ...mapGetters(["userInfo"]),
    },
    mounted(){
       this.timer = setInterval(()=>{
         this.refreshChange()
       },600000)
    },
    destroyed() {
    // 组件卸载时清除定时器
        if (this.timer) {
          clearInterval(this.timer);
        }
    },
    methods: {
      doAuditRefuseHandle(item){
        this.refuseItem = item
        this.openRefuseFlag = true
      },
      // 拒绝审核
      async doAuditRefuseConfirmHandle(formName){
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
               await doAudit({recordId:this.refuseItem.task_recordid,aduitId:this.refuseItem.id,status:3,remark:this.ruleForm.mark})
               this.openRefuseFlag = false
              this.page.currentPage = 1;
              this.getRecordListById(this.rowData.id)
              this.onLoad(this.page);
            }
          })
      },
      handleClose(){
        this.openSourceFlag=false
        this.openTaskFlag = true
      },
      viewCusDetail(row){
        this.activeCusName = 'cusFirst'
        if(row.resource){
          this.resourceImgArr = row.resource.split(',')
        }else{
          this.resourceImgArr = []
        }
        const remark = row.remark
        row.outUrl = this.getUrlFromStr(remark)
        this.feedRow = row
        this.openTaskFlag = false
        this.openSourceFlag = true
      },
      getUrlFromStr(text){
        const urlPattern = /(https?:\/\/[^\s]+)/g;
        const result = text.match(urlPattern)||'';
        return result;
      },
      openOutUrl(url){
        window.open(url)
      },
      async doAuditHandle(params,status){
        //发起支付任务
          const resData = await weixinPay({id:params.task_recordid})
          const message = resData.data.data.message
          if(message){
            this.$message({
              type: "error",
              message: message
            });
            return
          }else{
            this.$message({
              type: "success",
              message: '支付提交成功'
            });
          }
          if(resData.data.data.batch_id){
            await doAudit({recordId:params.task_recordid,aduitId:params.id,status})
            this.page.currentPage = 1;
            this.getRecordListById(this.rowData.id)
            this.onLoad(this.page);
          }
      },
      async getResourceList(ids){
        const resData = await findResourceByIds({ids})
        this.resourceArr = resData.data.data[0].artContent;
      },
      async getRecordListById(id){
          const resData = await getRecordList({recordId:id})
          this.feedbackResource = resData.data.data;
      },
      handleTabsClick(tab){
        if(tab.index == 1){
          this.getResourceList(this.rowData.resource)
        }else if(tab.index == 2){
          this.getRecordListById(this.rowData.id)
        }
      },
      clickViewDetail(row){
        this.rowData = row;
        this.feedbackResource = []
        this.addFormData = row;
        this.activeName = 'first'
        this.openTaskFlag = true
      },
       transteRecoredStatus(type){
        if(type == 1){
          return '待审核'
        }else if(type == 2){
          return '已审核'
        }else if(type == 3){
          return '已拒绝'
        }
      },
      transteStatus(type){
        if(type == 1){
          return '待审核'
        }else if(type == 2){
          return '已审核'
        }else if(type == 3){
          return '已拒绝'
        }else if(type == 4){
          return '待反馈'
        }
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      beforeOpen(done, type) {
        done();
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList({current:page.currentPage, size:page.pageSize,}).then(res => {
          const resData = res.data.data.list;
          this.page.total = res.data.data.total;
          resData.forEach(item=>{
            item.time = [item.startTime,item.endTime]
          })
          this.data = resData;
          this.loading = false;
        });
      }
    }
  };
</script>
<style lang="scss" scoped>
.refuse-box{
  max-width: 280px;
  line-height: 26px;
}
.img-box{
  display: flex;
  justify-content: center;
  img{
    margin-right: 10px;
    margin-bottom: 10px;
  }
  video{
    margin-bottom: 10px
  }
}
.aduit-box{
  display: flex;
  align-items: center;
  height: 40px;
  border-bottom: 1px solid  #ccc;
  justify-content: space-between;
  .left{
    display: flex;
    align-items: center;
    div{
      margin-right: 10px;
    }
  }
  .right{
    display: flex;
    align-items: center;
  }

}
</style>
